package com.mt.course.service.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;
import com.mt.common.PagerInfo;
import com.mt.common.ServiceResult;
import com.mt.common.util.ConvertUtil;
import com.mt.common.util.StringUtil;
import com.mt.course.entity.CourseEntity;
import com.mt.course.entity.CourseTeacherRelateEntity;
import com.mt.course.mapper.CourseEntityMapper;
import com.mt.course.mapper.CourseTeacherRelateEntityMapper;

@Component
public class CourseServiceModel {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(CourseServiceModel.class);

    @Autowired
    private CourseEntityMapper courseEntityMapper;

    @Autowired
    private CourseTeacherRelateEntityMapper courseTeacherRelateEntityMapper;

    public ServiceResult<List<CourseEntity>> selectList(Map<String, Object> params, PagerInfo<?> pagerInfo) {
        Assert.notNull(this.courseEntityMapper, "Property 'courseEntityMapper' is required.");
        ServiceResult<List<CourseEntity>> result = new ServiceResult<List<CourseEntity>>();
        try {
            if (pagerInfo != null) {
                PageHelper.startPage(pagerInfo.getPageIndex(), pagerInfo.getPageSize());
            }

            result.setResult(this.courseEntityMapper.selectList(params));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[CourseServiceModel][selectList]：query selectList occur exception", e);
        }
        return result;
    }

    public ServiceResult<CourseEntity> selectInfo(Map<String, Object> params) {
        Assert.notNull(this.courseEntityMapper, "Property 'courseEntityMapper' is required.");
        ServiceResult<CourseEntity> result = new ServiceResult<CourseEntity>();
        try {
            result.setResult(this.courseEntityMapper.selectByPrimaryKey(params));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[CourseServiceModel][selectInfo]：query selectInfo occur exception", e);
        }
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ServiceResult<Integer> insert(CourseEntity courseEntity) {
        Assert.notNull(this.courseEntityMapper, "Property 'courseEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int id = 0;
        Date now = new Date();
        try {
            int save = this.courseEntityMapper.insert(courseEntity);
            if (save > 0) {
                id = courseEntity.getCourseId();
                courseEntity.setCourseNo(StringUtil.addZeroForNum(String.valueOf(id), 8));
                courseEntityMapper.updateByPrimaryKeySelective(courseEntity);
            }
            if (!StringUtil.isEmpty(courseEntity.getTeacherId())) {
                String[] teacherIdArray = courseEntity.getTeacherId().split(",");
                if (teacherIdArray != null) {
                    List<CourseTeacherRelateEntity> courseTeacherList = new ArrayList<CourseTeacherRelateEntity>();
                    for (int i = 0; i < teacherIdArray.length; i++) {
                        CourseTeacherRelateEntity entity = new CourseTeacherRelateEntity();
                        entity.setCourseId(id);
                        entity.setTeacherId(ConvertUtil.toInt(teacherIdArray[i], 0));
                        entity.setCreateTime(now);
                        courseTeacherList.add(entity);
                    }
                    if (courseTeacherList.size() > 0) {
                        courseTeacherRelateEntityMapper.insertList(courseTeacherList);
                    }
                }
            }

            // 创建课程与讲师的关联表数据
            result.setResult(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[CourseServiceModel][insert]：query insert occur exception", e);
            throw new RuntimeException(e.getMessage());
        }
        return result;
    }

    public ServiceResult<Integer> updateRelate(CourseEntity courseEntity) {
        Assert.notNull(this.courseEntityMapper, "Property 'courseEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int courseId = 0;
        Date now = new Date();
        try {
            int save = this.courseEntityMapper.updateByPrimaryKeySelective(courseEntity);
            if (save > 0) {
                courseId = courseEntity.getCourseId();

                if (!StringUtil.isEmpty(courseEntity.getTeacherId())) {
                    // 修改课程时，由于讲师字段以字符串拼接方式保存在一个字段内，并且一对多方式存在关联表，无法判断是否修改，所以全部删除关联关系，再创建
                    courseTeacherRelateEntityMapper.deleteByCourseId(courseId);
                    String[] teacherIdArray = courseEntity.getTeacherId().split(",");
                    if (teacherIdArray != null) {
                        List<CourseTeacherRelateEntity> courseTeacherList = new ArrayList<CourseTeacherRelateEntity>();
                        for (int i = 0; i < teacherIdArray.length; i++) {
                            CourseTeacherRelateEntity entity = new CourseTeacherRelateEntity();
                            entity.setCourseId(courseId);
                            entity.setTeacherId(ConvertUtil.toInt(teacherIdArray[i], 0));
                            entity.setCreateTime(now);
                            courseTeacherList.add(entity);
                        }
                        if (courseTeacherList.size() > 0) {
                            courseTeacherRelateEntityMapper.insertList(courseTeacherList);
                        }
                    }
                }
            }
            result.setResult(courseId);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[CourseServiceModel][updateByPrimaryKeySelective]:query update occur exception", e);
        }
        return result;
    }

    public ServiceResult<Integer> updateByPrimaryKeySelective(CourseEntity courseEntity) {
        Assert.notNull(this.courseEntityMapper, "Property 'courseEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int id = 0;
        try {
            int save = this.courseEntityMapper.updateByPrimaryKeySelective(courseEntity);
            if (save > 0) {
                id = courseEntity.getCourseId();
            }
            result.setResult(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[CourseServiceModel][updateByPrimaryKeySelective]:query update occur exception", e);
        }
        return result;
    }

    public ServiceResult<Integer> deleteByPrimaryKey(Integer courseId) {
        Assert.notNull(this.courseEntityMapper, "Property 'courseEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int save = 0;
        try {
            save = this.courseEntityMapper.deleteByPrimaryKey(courseId);
            result.setResult(save);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[CourseServiceModel][updateByPrimaryKeySelective]:query update occur exception", e);
        }
        return result;
    }
}
